package com.haiertvbic.tvnow.network;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.haiertvbic.tvnow.util.SLog;

public class ImageUtil {
	private static final String TAG = "ImageUtil";
	public static String haierFlag = "-1";
	public static String offset = "0";

	/**
	 * 将传来的加密图片流解密返还一个普通流
	 * 
	 * @param inSrteam
	 * @return
	 */
	public static InputStream decipheringPic(InputStream inSrteam)
			throws IOException {
		String key = "haiertvbic_auth";
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = inSrteam.read(buf)) != -1) {
			baos.write(buf, 0, len);
		}
		byte[] decodeContent = XOR(baos.toByteArray(), key);
		return new ByteArrayInputStream(decodeContent);
	}

	public static byte[] XOR(byte[] source, String key) {
		byte[] keyBytes = null;
		try {
			keyBytes = key.getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] result = source.clone();
		for (int i = 0; i < keyBytes.length && i < source.length; i++) {
			result[i] = (byte) (source[i] ^ keyBytes[i]);
		}
		return result;
	}

	public static Bitmap getPicData(String urlString) {
		return getPicData(urlString, false);
	}

	/**
	 * 请求图片的方法，
	 * 
	 * @param url
	 * @param isDeciph
	 *            是否加密
	 * @return 返回一个图片的流
	 */
	public static Bitmap getPicData(String url, boolean isDeciph) {
		InputStream inSrteam = null;
		Bitmap bitmap = null;
		try {
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(1000);
			conn.setRequestMethod("POST");
			// conn.setRequestMethod("GET");
			if (conn.getResponseCode() == 200) {
				inSrteam = conn.getInputStream();
				if (isDeciph) {
					inSrteam = decipheringPic(inSrteam);
				}
				bitmap = BitmapFactory.decodeStream(inSrteam);
			}

		} catch (OutOfMemoryError e) {// 这个是不能捕捉的
			if (e != null) {
				SLog.i(TAG, "==Memory overflow：" + e.toString());
			}
		} catch (Exception e) {
			if (e != null) {
				SLog.i(TAG, "==Exception：" + e.toString());
			}
		} finally {
			if (inSrteam != null) {
				try {
					inSrteam.close();
					inSrteam = null;
				} catch (IOException e) {
					if (e != null) {
						SLog.i(TAG, "==IOException：" + e.toString());
					}
				}
			}
		}
		return bitmap;
	}
}
